﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Cnblogs.Service;
using System.Collections.ObjectModel;
using Microsoft.Phone.Shell;

namespace Cnblogs
{
    public partial class BloggerPage : PhoneApplicationPage
    {
        private bool isLoaded = false;
        private int _postPage = 1;
        private string blogApp = "";
        private string blogName = "";
        public ObservableCollection<Entry> Items = new ObservableCollection<Entry>();

        public BloggerPage()
        {
            InitializeComponent();
            lbx_posts.ItemsSource = Items;
        }

        private void Appbar_Search_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(Constants.P_SearchPage, UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!isLoaded)
            {
                isLoaded = true;
                if (NavigationContext.QueryString.ContainsKey("name"))
                {
                    blogName = NavigationContext.QueryString["name"];
                    this.PageTitle.Text = NavigationContext.QueryString["name"];
                }
                if (NavigationContext.QueryString.ContainsKey("blogapp"))
                {
                    blogApp = NavigationContext.QueryString["blogapp"];
                    loadData();
                }
            }
            base.OnNavigatedTo(e);
        }

        private bool isRequesting = false;
        private void loadData(bool isMore = false)
        {
            if (isRequesting) return;
            isRequesting = true;
            if (isMore)
            {
                _postPage++;
            }
            GlobalIndicator.Instance.StartBusy(Constants.L_GettingData);
            FeedService.Request(ServiceType.Blogger,
                new NewsData
                {
                    Key = blogApp,
                    PageIndex = _postPage,
                    PageSize = GlobalFunc.PageSize
                },
                (obj, isSuccess) =>
                {
                    isRequesting = false;
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        if (isSuccess && obj is BloggerFeed)
                        {
                            if (!isMore)
                            {
                                Items.Clear();    
                            }                            
                            var feeds = (obj as BloggerFeed);
                            if (feeds.Items!=null)
                            {
                                //api的bug：请求20条却返回10条数据
                                btn_loadmore.Visibility = feeds.Items.Length == 10 ? Visibility.Visible : Visibility.Collapsed;
                                foreach (var item in feeds.Items)
                                {
                                    Items.Add(item);
                                }
                            }
                            
                            this.PageTitle.Text = feeds.AuthorInfo.Name;
                            this.tbk_postCountTip.Text = "文章数：";
                            this.tbk_postCount.Text = feeds.PostCount;
                        }
                        else
                        {
                            if (lbx_posts.Items.Count==0)
                            {
                                this.btn_loadmore.Content = "暂无文章";
                                btn_loadmore.IsEnabled = false;
                            }
                        }
                    });
                    GlobalIndicator.Instance.StopBusy();
                });
        }

        private void SelectItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var grd = sender as Grid;
            if (grd != null)
            {
                var entry = grd.DataContext as Entry;
                if (entry != null)
                {
                    (App.Current as App).CurrentEntry = entry;
                    if ((App.Current as App).PostItems != Items)
                    {
                        (App.Current as App).PostItems = Items;
                    }
                    NavigationService.Navigate(new Uri(Constants.P_PostBodyPage, UriKind.Relative));
                }
            }
        }

        private void btn_loadmore_click(object sender, RoutedEventArgs e)
        {
            loadData(true);
        }

        private void Appbar_Pin_Click(object sender, EventArgs e)
        {
            Uri u = new Uri(Constants.P_BloggerPage + "?blogapp=" + blogApp + "&name=" + blogName, UriKind.Relative);
            if (ShellTileHelper.IsPinned(u))
                return;
            StandardTileData std = new StandardTileData
            {
                Title = blogName,
                BackgroundImage = new Uri("Background.png", UriKind.Relative),
                //BackTitle = XiamiLanguages.AppTitle,
                //BackContent = "专辑数：" + SelectArtist.album_count,
            };
            ShellTileHelper.Pin(u, std);
        }

        private void Appbar_Download_Click(object sender, EventArgs e)
        {
            MessageBox.Show("哎呦，离线下载还没做哦");
        }
    }
}